package com.intel.factorytest.activity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.intel.factorytest.R;
import com.intel.factorytest.cfparser.ConfigFileParseUtil;
import com.intel.factorytest.cfparser.concrete.AConfigFileParser;
import com.intel.factorytest.cfparser.concrete.PropertiesConfParser;
import com.intel.factorytest.constants.PropertiesConstants;
import com.intel.factorytest.log.LogWriter;
import com.intel.factorytest.util.PropertiesUtil;

public class SoftwareInfo_pref extends PreferenceActivity{
    
    static final String TAG = "SoftwareInfo::";

//    String mat_ver_key = "fih_factorytest_mat_version_pref";
    String build_key ="fih_factorytest_build_version_pref";
//    String sn_key = "fih_factorytest_sn_pref";
//    String imei_key = "fih_factorytest_imei_pref";
//    String bt_key = "fih_factorytest_bt_pref";
//    String wf_key = "fih_factorytest_wifi_addr_pref";
    private WifiManager mWifiManager;
    private WifiInfo wifiInfo; 
    private BluetoothAdapter mAdapter;
    private PreferenceScreen bt_pref; 
    
    private int widthScreen;
    private int heightScreen;
    
    private Button mSucBtn;
    private Button mFailBtn;
    private Button mRepBtn;
    
    private String sys_service_for_pcba ="SYSTEM_SERVICE_FOR_PCBA_TEST";
    private boolean isPcba = false;
    private boolean is_pass = false;
    
    private String mSWBuildVersion;
//    private String mSWSerialNumber;
//    private String mSWBTMac;
//    private String mSWWifiMac;
//    private String mSWMatVersion;
    
    private boolean isBuildVersionOK = false;
//    private boolean isSerialNumberOK = false;
//    private boolean isBTMacOK = false;
//    private boolean isWifiMacOK = false;
//    private boolean isMatVersionOK = false;
    
    protected int test_pos = 0;
    protected static final String TEST_ITEM = "test_item";
    protected static final String ITEM_NAME = "item_name";
    protected static final String TEST_ITEM_RESULT = "test_item_result";
    public static final String TEST_LOG_RESULT = "log_result";
    
    protected String sys_service ="SYSTEM_SERVICE_TEST";
    protected boolean isSystemTest = false;
    
    protected String itemName;
    
    protected String logFileName;
    protected LogWriter.TestCase tc;
    private int orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        test_pos = intent.getIntExtra(TEST_ITEM, -1);
        isPcba = intent.getIntExtra(sys_service_for_pcba, 0) == 1 ? true : false;
        isSystemTest = intent.getIntExtra(sys_service, 0) == 1 ? true : false;
        itemName = intent.getStringExtra(ITEM_NAME);
        logFileName = intent.getStringExtra(LogWriter.LogFileNameTag);
        tc = LogWriter.TestCase.getSingletonInstanse(test_pos, itemName, "", is_pass);
        
        if (isSystemTest) {
            String orientationStr = intent.getStringExtra("sd_orientation");
            if (orientationStr != null) {
                Log.i("util","orientationStr = " + orientationStr);
                if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
                    orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
                    super.setRequestedOrientation(orientation);
                    
                } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
                    orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
                    super.setRequestedOrientation(orientation);
                    
                }
            } else {
                // 整机测试中没有配屏幕方向的情况，保持与系统一样的特性
            }
        }
        
        initScreenSize();
        initSoftwareInfosProps();

        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mAdapter.enable();
        mWifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        mWifiManager.setWifiEnabled(true);

        addPreferencesFromResource(R.xml.softwareinfopref);
        
        // add buttons on bottom
        RelativeLayout resultBtnLayout = (RelativeLayout) View.inflate(this, R.layout.result_button_layout_preference, null);
        mSucBtn = (Button) resultBtnLayout.findViewById(R.id.success_button);
        RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(100, 80);
        params1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params1.setMargins(80, 0, 0, heightScreen - 500);
        resultBtnLayout.updateViewLayout(mSucBtn, params1);
        mSucBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                
            }
        });
        
        mFailBtn = (Button) resultBtnLayout.findViewById(R.id.fail_button);
        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(100, 80);
        params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params2.setMargins(80, 0, 0, heightScreen - 500);
//        params2.setMarginStart(5);
        resultBtnLayout.updateViewLayout(mFailBtn, params2);
        mFailBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                is_pass = false;
                finish();
            }
        });
        
        mRepBtn = (Button) resultBtnLayout.findViewById(R.id.repeat_button);
        RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(100, 80);
        params3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        System.out.println("tangjun software info: heightScreen=" + heightScreen + ",bottom margin=" + (heightScreen-500));
        params3.setMargins(0, 0, 80, heightScreen - 500);
        resultBtnLayout.updateViewLayout(mRepBtn, params3);
        mRepBtn.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SoftwareInfo_pref.this.recreate();
            }
        });
        
        ListView lv = getListView();
        lv.addFooterView(resultBtnLayout);

//        PreferenceScreen mat_ver_pref = (PreferenceScreen) findPreference(mat_ver_key);
//        mat_ver_pref.setSummary(getMATNum());

        PreferenceScreen buildversion_pref = (PreferenceScreen) findPreference(build_key);
        buildversion_pref.setSummary(getBuildNum());
        isBuildVersionOK = check(mSWBuildVersion, getBuildNum().toString());
//        firmwareversion_pref.setSummary(getFirmwareVersion());//yjcui        
//        PreferenceScreen sn_pref = (PreferenceScreen) findPreference(sn_key);
//        sn_pref.setSummary(getSnNum());
//        isSerialNumberOK = check(mSWSerialNumber, getSnNum().toString());

//        PreferenceScreen imei_pref = (PreferenceScreen) findPreference(imei_key);
//        imei_pref.setSummary(getImei());
//        PreferenceScreen wf_pref = (PreferenceScreen) findPreference(wf_key);
//        wf_pref.setSummary(getWf());
//        isWifiMacOK = check(mSWWifiMac, getWf().toString());
        
//        bt_pref = (PreferenceScreen) findPreference(bt_key);
//        isBTMacOK = check(mSWBTMac, getBt().toString());
        
//        PreferenceScreen mat_pref = (PreferenceScreen) findPreference(mat_ver_key);
//        mat_pref.setSummary(getMATNum());
//        isMatVersionOK = check(mSWMatVersion, getMATNum());

        m_handler.sendEmptyMessageDelayed(0, 1000);
/*        PreferenceScreen kernelversion_pref = (PreferenceScreen) findPreference("fih_factorytest_kernel_version_pref");
        kernelversion_pref.setSummary(getFormattedKernelVersion());
        PreferenceScreen bpversion_pref = (PreferenceScreen) findPreference("fih_factorytest_bp_version_pref");
        bpversion_pref.setSummary(getBPVersion());
        PreferenceScreen oplversion_pref = (PreferenceScreen) findPreference("fih_factorytest_opl_version_pref");
        oplversion_pref.setSummary(getOPLVersion());
        PreferenceScreen release_time_pref = (PreferenceScreen) findPreference("fih_factorytest_release_time_pref");
        release_time_pref.setSummary(getReleaseTime());
*/
    }
    
    private CharSequence getFirmwareVersion() {
        //intel
        return   "OMS2.6" 
            +"("
            +android.os.SystemProperties.get("ro.build.revision")
            +")";
    }
    
    private CharSequence getBlobVersion() {
        String blobVersionStr;
        try {
            BufferedReader reader = new BufferedReader(new FileReader("/sys/fih_sw_info/fih_blob_version"),256);
            try{
            blobVersionStr = reader.readLine();
            }finally{
                reader.close();
            }
            return blobVersionStr;            
        } catch (FileNotFoundException e) {
            return "Unavailable";
        } catch (IOException e) {
            return "Unavailable";
        }
    }

    private String getFormattedKernelVersion() {
        String intel_mat_procVersionStr;

        try {
            BufferedReader intel_mat_reader = new BufferedReader(new FileReader(
                    "/proc/version"), 256);
            try {
                intel_mat_procVersionStr = intel_mat_reader.readLine();
            } finally {
                intel_mat_reader.close();
            }

            final String INTEL_MAT_PROC_VERSION_REGEX = "\\w+\\s+" + "\\w+\\s+"
                    + "([^\\s]+)\\s+"
                    + "\\(([^\\s@]+(?:@[^\\s.]+)?)[^)]*\\)\\s+"
                    + "\\((?:[^(]*\\([^)]*\\))?[^)]*\\)\\s+" + "([^\\s]+)\\s+"
                    + "(?:PREEMPT\\s+)?" + "(.+)";

            Pattern ptn = Pattern.compile(INTEL_MAT_PROC_VERSION_REGEX);
            Matcher mtch = ptn.matcher(intel_mat_procVersionStr);

            if (!mtch.matches()) {
                Log.e(TAG, "Regex did not match on /proc/version: " + intel_mat_procVersionStr);
                return "Unavailable";
            } else if (mtch.groupCount() < 4) {
                Log.e(TAG, "Regex match on /proc/version only returned " + mtch.groupCount() + " groups");
                return "Unavailable";
            } else {
                return (new StringBuilder(mtch.group(1)).append("\n")
                        .append(mtch.group(2)).append(" ").append(mtch.group(3))
                        .append("\n").append(mtch.group(4))).toString();
            }
        } catch (IOException e1) {
            Log.e(TAG, "IO Exception when getting kernel version for Device Info screen", e1);
            return "Unavailable";
        }
    }
    
    private CharSequence getBPVersion() {
        String bpVersionStr;
        try {
            BufferedReader reader = new BufferedReader(new FileReader("/sys/fih_sw_info/fih_bp_version"),256);
            try{
                bpVersionStr = reader.readLine();
            }finally{
                reader.close();
            }
            return bpVersionStr;            
        } catch (FileNotFoundException e) {
            return "Unavailable";
        } catch (IOException e) {
            return "Unavailable";
        }
    }
    
    private CharSequence getOPLVersion() {
        String oplVersionStr;
        try {
            BufferedReader reader = new BufferedReader(new FileReader("/opl/ver/oplver"),256);
            try{
                oplVersionStr = reader.readLine();
            }finally{
                reader.close();
            }
            return oplVersionStr;            
        } catch (FileNotFoundException e) {
            return "Unavailable";
        } catch (IOException e) {
            return "Unavailable";
        }
    }

    private CharSequence getReleaseTime() {
        return android.os.SystemProperties.get("ro.build.date"); 
    }
    private String getMATNum() {
        return "V2.1.5";
    }
    private CharSequence getBuildNum() {
        return Build.DISPLAY;
//        return Build.SOFTWARE;
    }
    private CharSequence getSnNum() {
        return Build.SERIAL;
    }
    private CharSequence getImei() {
        android.telephony.TelephonyManager TM = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);    
        return TM.getDeviceId();
    }
    private CharSequence getBt() {
        String address = mAdapter.isEnabled() ? mAdapter.getAddress() : "";
        return address;
    }
    private CharSequence getWf() {
        wifiInfo = mWifiManager.getConnectionInfo();
        String macAddress = wifiInfo == null ? "" : wifiInfo.getMacAddress();
        return  macAddress;
    }

    Handler m_handler = new Handler()
    {
        public void handleMessage(Message msg) {
            Log.d(TAG,"handle message msg.what ="+msg.what);
            switch (msg.what)
            {
            case 0:
//                bt_pref.setSummary(getBt());
                is_pass = checkResult();
                if (is_pass) {
                    finish();
                } else {
                    // verify failed
                }
                break;
            }
        }
    };
    
    @Override
    public void finish() {
//        try {
//            System.out.println("tangjun activity finish. logFileName=" + logFileName);
//            tc = LogWriter.TestCase.getSingletonInstanse(test_pos, itemName, "", is_pass);
//            LogWriter.write(logFileName, tc);
//        } catch (IOException e) {
//            //isLogSuc = false;
//        } finally {
//            
//        }
        setTestResult(true);
        super.finish();
    }
    
    protected void setTestResult (boolean isLogSuc) {
        Intent data = new Intent();
        data.putExtra(TEST_ITEM, test_pos);
        data.putExtra(TEST_ITEM_RESULT, is_pass);
        data.putExtra(TEST_LOG_RESULT, isLogSuc);
        data.putExtra(LogWriter.LogFileNameTag, logFileName);
        setResult(0, data);
    }

    private void initScreenSize() {
        // get screen size
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.widthScreen = dm.widthPixels;
        this.heightScreen = dm.heightPixels;
        
    }
    
    private void initSoftwareInfosProps() {
        PropertiesConfParser propParser = (PropertiesConfParser) ConfigFileParseUtil.getConfParserConcrete(this, AConfigFileParser.EXTENSION_PROPERTISE);
        PropertiesUtil properties = propParser.getProperties(isPcba);
        mSWBuildVersion = properties.getProperty(PropertiesConstants.KEY_SWINFO_BUILD_VERSION, "");
//        mSWSerialNumber = properties.getProperty(PropertiesConstants.KEY_SWINFO_SN, "");
//        mSWMatVersion = properties.getProperty(PropertiesConstants.KEY_SWINFO_MAT_VERSION, "");
//        mSWWifiMac = properties.getProperty(PropertiesConstants.KEY_SWINFO_WIFI_MAC, "");
//        mSWBTMac = properties.getProperty(PropertiesConstants.KEY_SWINFO_BT_MAC, "");
                
    }
    
    private boolean check(String origin, String compare) {
        if (origin == null || compare == null) {
            return false;
        }
        System.out.println("tangjun check software info: expect = " + origin + ", actual = " + compare);
        return origin.equals(compare);
    }
    
    private boolean checkResult() {
        return isBuildVersionOK/* && isSerialNumberOK && isWifiMacOK && isBTMacOK && isMatVersionOK*/;
    }
}
